import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '../views/SimpleLogin.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue'),
    meta: { requiresAuth: true }
  },
  // 医保数据维护部门路由
  {
    path: '/admin',
    name: 'admin',
    component: () => import(/* webpackChunkName: "admin-layout" */ '../views/AdminView.vue'),
    meta: { requiresAuth: true, role: 'admin', keepAlive: true },
    children: [
      {
        path: '',
        name: 'admin-home',
        component: () => import(/* webpackChunkName: "admin-home" */ '../views/admin/AdminHome.vue'),
        meta: { requiresAuth: true, role: 'admin', keepAlive: true }
      },
      {
        path: 'medical-insurance-data',
        name: 'medical-insurance-data',
        component: () => import(/* webpackChunkName: "admin-insurance" */ '../views/admin/MedicalInsuranceData.vue'),
        meta: { requiresAuth: true, role: 'admin', keepAlive: true }
      },
      {
        path: 'treatment-data',
        name: 'treatment-data',
        component: () => import(/* webpackChunkName: "admin-treatment" */ '../views/admin/TreatmentData.vue'),
        meta: { requiresAuth: true, role: 'admin', keepAlive: true }
      },
      {
        path: 'medical-service-data',
        name: 'medical-service-data',
        component: () => import(/* webpackChunkName: "admin-service" */ '../views/admin/MedicalServiceData.vue'),
        meta: { requiresAuth: true, role: 'admin', keepAlive: true }
      },
      // 已移除功能的占位符路由
      {
        path: 'drug-ratio',
        name: 'drug-ratio',
        component: () => import(/* webpackChunkName: "admin-ratio" */ '../views/admin/DrugRatio.vue'),
        meta: { requiresAuth: true, role: 'admin', keepAlive: true }
      },
      {
        path: 'hospital-level-three-ratio',
        name: 'hospital-level-three-ratio',
        component: () => import(/* webpackChunkName: "admin-ratio" */ '../views/admin/HospitalLevelThreeRatio.vue'),
        meta: { requiresAuth: true, role: 'admin', keepAlive: true }
      },
      {
        path: 'hospital-level-two-ratio',
        name: 'hospital-level-two-ratio',
        component: () => import(/* webpackChunkName: "admin-ratio" */ '../views/admin/HospitalLevelTwoRatio.vue'),
        meta: { requiresAuth: true, role: 'admin', keepAlive: true }
      },
      {
        path: 'hospital-level-one-ratio',
        name: 'hospital-level-one-ratio',
        component: () => import(/* webpackChunkName: "admin-ratio" */ '../views/admin/HospitalLevelOneRatio.vue'),
        meta: { requiresAuth: true, role: 'admin', keepAlive: true }
      }
    ]
  },
  // 医院角色路由
  {
    path: '/hospital',
    name: 'hospital',
    component: () => import(/* webpackChunkName: "hospital-layout" */ '../views/HospitalView.vue'),
    meta: { requiresAuth: true, role: 'hospital', keepAlive: true },
    children: [
      {
        path: '',
        name: 'hospital-home',
        component: () => import(/* webpackChunkName: "hospital-home" */ '../views/hospital/HospitalHome.vue'),
        meta: { requiresAuth: true, role: 'hospital', keepAlive: true }
      },
      {
        path: 'registration',
        name: 'hospital-registration',
        component: () => import(/* webpackChunkName: "hospital-patient" */ '../views/hospital/PatientRegistration.vue'),
        meta: { requiresAuth: true, role: 'hospital', keepAlive: true }
      },
      // 患者诊断相关路由
      {
        path: 'patient-selection',
        name: 'hospital-patient-selection',
        component: () => import(/* webpackChunkName: "hospital-patient" */ '../views/hospital/PatientSelection.vue'),
        meta: { requiresAuth: true, role: 'hospital', keepAlive: true }
      },
      {
        path: 'admission-diagnosis',
        name: 'hospital-admission-diagnosis',
        component: () => import(/* webpackChunkName: "hospital-patient" */ '../views/hospital/InpatientDiagnosis.vue'),
        meta: { requiresAuth: true, role: 'hospital', keepAlive: true }
      },
      {
        path: 'main-diagnosis',
        name: 'hospital-main-diagnosis',
        component: () => import(/* webpackChunkName: "hospital-patient" */ '../views/hospital/MainDiagnosis.vue'),
        meta: { requiresAuth: true, role: 'hospital', keepAlive: true }
      },
      {
        path: 'other-diagnosis',
        name: 'hospital-other-diagnosis',
        component: () => import(/* webpackChunkName: "hospital-patient" */ '../views/hospital/OtherDiagnosis.vue'),
        meta: { requiresAuth: true, role: 'hospital', keepAlive: true }
      },
      // 患者医嘱相关路由
      {
        path: 'patient-selection-order',
        name: 'hospital-patient-selection-order',
        component: () => import(/* webpackChunkName: "hospital-order" */ '../views/hospital/PatientOrderSelection.vue'),
        meta: { requiresAuth: true, role: 'hospital', keepAlive: true }
      },
      {
        path: 'drug-prescription',
        name: 'hospital-drug-prescription',
        component: () => import(/* webpackChunkName: "hospital-order" */ '../views/hospital/DrugPrescription.vue'),
        meta: { requiresAuth: true, role: 'hospital', keepAlive: true }
      },
      {
        path: 'treatment-order',
        name: 'hospital-treatment-order',
        component: () => import(/* webpackChunkName: "hospital-order" */ '../views/hospital/TreatmentOrder.vue'),
        meta: { requiresAuth: true, role: 'hospital', keepAlive: true }
      },
      {
        path: 'medical-service',
        name: 'hospital-medical-service',
        component: () => import(/* webpackChunkName: "hospital-order" */ '../views/hospital/MedicalService.vue'),
        meta: { requiresAuth: true, role: 'hospital', keepAlive: true }
      }
    ]
  },
  // 医保报销角色路由
  {
    path: '/reimbursement',
    name: 'reimbursement',
    component: () => import(/* webpackChunkName: "reimbursement-layout" */ '../views/ReimbursementView.vue'),
    meta: { requiresAuth: true, role: 'reimbursement', keepAlive: true },
    children: [
      {
        path: '',
        name: 'reimbursement-home',
        component: () => import(/* webpackChunkName: "reimbursement-home" */ '../views/reimbursement/ReimbursementHome.vue'),
        meta: { requiresAuth: true, role: 'reimbursement', keepAlive: true }
      },
      {
        path: 'participant-info',
        name: 'participant-info',
        component: () => import(/* webpackChunkName: "reimbursement-info" */ '../views/reimbursement/ParticipantInfo.vue'),
        meta: { requiresAuth: true, role: 'reimbursement', keepAlive: true }
      },
      {
        path: 'participant-expense',
        name: 'participant-expense',
        component: () => import(/* webpackChunkName: "reimbursement-expense" */ '../views/reimbursement/ParticipantExpense.vue'),
        meta: { requiresAuth: true, role: 'reimbursement', keepAlive: true }
      },
      {
        path: 'participant-list',
        name: 'participant-list',
        component: () => import(/* webpackChunkName: "reimbursement-list" */ '../views/reimbursement/ParticipantList.vue'),
        meta: { requiresAuth: true, role: 'reimbursement', keepAlive: true }
      },
      {
        path: 'expense-reimbursement/:id',
        name: 'expense-reimbursement',
        component: () => import(/* webpackChunkName: "reimbursement-expense" */ '../views/reimbursement/ExpenseReimbursement.vue'),
        meta: { requiresAuth: true, role: 'reimbursement', keepAlive: true }
      },
      // 新增的医保报销系统页面路由
      {
        path: 'participant-detail/:id',
        name: 'participant-detail',
        component: () => import(/* webpackChunkName: "reimbursement-detail" */ '../views/reimbursement/ParticipantDetail.vue'),
        meta: { requiresAuth: true, role: 'reimbursement', keepAlive: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  // 滚动行为优化
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由加载进度追踪
let hasLoadedComponent = false
router.beforeResolve((to, from, next) => {
  // 若组件已经加载，直接进入
  if (hasLoadedComponent || !to.matched.length) {
    hasLoadedComponent = false
    return next()
  }

  // 找出未加载的异步组件
  const matched = router.resolve(to).matched
  const asyncComponents = []

  matched.forEach(record => {
    const component = record.components.default
    if (typeof component === 'function' && !component.displayed) {
      asyncComponents.push(component())
    }
  })

  // 如果没有需要加载的异步组件，直接进入
  if (!asyncComponents.length) {
    return next()
  }

  // 等待所有异步组件加载完成
  Promise.all(asyncComponents)
    .then(() => {
      hasLoadedComponent = true
      next()
    })
    .catch(err => {
      console.error('组件加载失败:', err)
      next()
    })
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token') // 简单的身份验证检查
  const userRole = localStorage.getItem('userRole') // 获取用户角色
  
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      next({ name: 'login' })
    } else {
      // 检查角色权限
      if (to.meta.role && to.meta.role !== userRole) {
        // 如果路由需要特定角色但用户角色不匹配
        if (userRole === 'admin') {
          next({ path: '/admin' })
        } else if (userRole === 'reimbursement') {
          next({ path: '/reimbursement' })
        } else if (userRole === 'hospital') {
          next({ path: '/hospital' })
        } else {
          next({ path: '/home' })
        }
      } else {
        next()
      }
    }
  } else {
    next()
  }
})

export default router

